<template>
  <div class="risk-container">
    <!-- 风险概览 -->
    <div class="risk-overview-card">
      <div class="card-header">
        <div class="title">风险概览</div>
        <div class="actions">
          <el-button type="text" class="update-btn">立即刷新</el-button>
          <el-button type="primary" size="small">刷新预警</el-button>
        </div>
      </div>
      <div class="overview-content">
        <div class="overview-item">
          <div class="item-label">风险评分</div>
          <div class="score-box">
            <div class="score-value">
              <span class="main-score">68</span>
              <span class="divider">/</span>
              <span class="total-score">100</span>
            </div>
            <div class="score-bar">
              <div class="progress-bg"></div>
              <div class="progress" :style="{ width: '68%' }"></div>
            </div>
          </div>
          <div class="score-desc">中等风险水平，需要关注</div>
        </div>
        <div class="overview-item">
          <div class="item-label">开放风险提醒</div>
          <div class="alert-count">7</div>
          <div class="alert-details">
            <span class="alert-type">严重：<span class="count severe">2</span></span>
            <span class="alert-type">高危：<span class="count high">3</span></span>
            <span class="alert-type">中危：<span class="count medium">2</span></span>
            <span class="alert-type">低危：<span class="count low">0</span></span>
          </div>
        </div>
        <div class="overview-item">
          <div class="item-label">资产保护率</div>
          <div class="protection-box">
            <div class="protection-value">82.5%</div>
            <div class="protection-bar">
              <div class="progress-bg"></div>
              <div class="progress" :style="{ width: '82.5%' }"></div>
            </div>
          </div>
          <div class="protection-desc">风控规则覆盖大部分资产</div>
        </div>
        <div class="overview-item">
          <div class="item-label">今日预警次数</div>
          <div class="warning-count">14</div>
          <div class="warning-trend">
            较昨日 <span class="trend-value up">+3</span> | 较上周 <span class="trend-value down">-8</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 实时风险预警 -->
    <div class="risk-alerts-card">
      <div class="card-header">
        <div class="title">实时风险预警</div>
        <div class="actions">
          <el-button type="text">更多</el-button>
          <el-button type="primary" size="small">查看详情</el-button>
        </div>
      </div>
      <div class="alerts-list">
        <div class="alert-item danger">
          <i class="el-icon-warning" />
          <div class="alert-content">
            <div class="alert-title">严重预警：BTC-USDT 日内下跌 5%，超过预警线 (3%)</div>
            <div class="alert-time">触发时间：2025-05-23 08:45:22 | 策略：趋势跟踪 #42</div>
          </div>
          <el-tag type="danger">紧急预警</el-tag>
        </div>
        <div class="alert-item warning">
          <i class="el-icon-warning" />
          <div class="alert-content">
            <div class="alert-title">ETH 市值比达到 55.2%，超过最大单一资产限制 (50%)</div>
            <div class="alert-time">触发时间：2025-05-23 09:12:05 | 策略：多策略组合 #45</div>
          </div>
          <el-tag type="warning">重要预警</el-tag>
        </div>
        <div class="alert-item info">
          <i class="el-icon-info" />
          <div class="alert-content">
            <div class="alert-title">SQL 价格波动超过 8%，高于预设阈值</div>
            <div class="alert-time">触发时间：2025-05-23 08:45:45 | 策略：波动交易 #45</div>
          </div>
          <el-tag>普通预警</el-tag>
        </div>
        <div class="alert-item info">
          <i class="el-icon-info" />
          <div class="alert-content">
            <div class="alert-title">BNB-USDT 波动下降 35%，影响策略执行</div>
            <div class="alert-time">触发时间：2025-05-23 08:32:18 | 策略：市场做市 #37</div>
          </div>
          <el-tag>普通预警</el-tag>
        </div>
        <div class="alert-item info">
          <i class="el-icon-info" />
          <div class="alert-content">
            <div class="alert-title">API 调用异常率接近阈值 (85%)</div>
            <div class="alert-time">触发时间：2025-05-23 08:30:40 | 影响策略：多个</div>
          </div>
          <el-tag>普通预警</el-tag>
        </div>
      </div>
    </div>

    <!-- 风险预警记录 -->
    <div class="risk-records-card">
      <div class="card-header">
        <div class="title">风险预警记录</div>
        <el-button type="success" size="small">添加预警</el-button>
      </div>
      <div class="records-content">
        <el-table :data="riskRecords" style="width: 100%">
          <el-table-column label="状态" width="80">
            <template slot-scope="scope">
              <div class="status-dot" :class="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="预警名称" />
          <el-table-column prop="threshold" label="预警阈值" width="120" />
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column prop="status" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.statusText }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" @click="handleRecord(scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 风险分析 -->
    <div class="risk-analysis-card">
      <div class="card-header">
        <div class="title">风险分析</div>
        <div class="actions">
          <el-button type="text">时间筛选</el-button>
          <el-button type="primary" size="small">查看趋势</el-button>
        </div>
      </div>
      <div class="analysis-content">
        <div class="chart-container">
          <div class="pie-chart" ref="riskDistribution"></div>
          <div class="line-chart" ref="riskTrend"></div>
        </div>
        <div class="risk-table">
          <el-table :data="riskAnalysis" style="width: 100%">
            <el-table-column prop="type" label="风险类型" />
            <el-table-column prop="count" label="触发次数" />
            <el-table-column prop="trend" label="变化趋势">
              <template slot-scope="scope">
                <span :class="scope.row.trend >= 0 ? 'up' : 'down'">
                  {{ scope.row.trend > 0 ? '↑' : '↓' }} {{ Math.abs(scope.row.trend) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="level" label="风险等级">
              <template slot-scope="scope">
                <el-tag :type="getRiskLevelType(scope.row.level)">{{ scope.row.level }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="suggestion" label="建议措施" />
          </el-table>
        </div>
      </div>
    </div>

    <!-- 风险设置 -->
    <div class="risk-settings-card">
      <div class="card-header">
        <div class="title">风控设置</div>
        <el-button type="primary" size="small">保存设置</el-button>
      </div>
      <div class="settings-content">
        <div class="settings-section">
          <div class="section-title">全局风控设置</div>
          <el-form :model="riskSettings" label-width="120px">
            <el-form-item label="风控检查频率">
              <el-select v-model="riskSettings.checkFrequency" style="width: 100%">
                <el-option label="每5分钟" value="5min" />
                <el-option label="每10分钟" value="10min" />
                <el-option label="每30分钟" value="30min" />
              </el-select>
            </el-form-item>
            <el-form-item label="风险处理方式">
              <el-select v-model="riskSettings.handleMode" style="width: 100%">
                <el-option label="自动处理低风险，通知高风险" value="auto" />
                <el-option label="全部手动处理" value="manual" />
              </el-select>
            </el-form-item>
            <el-form-item label="通知方式">
              <div class="notify-options">
                <el-checkbox v-model="riskSettings.notifyMethods.email">电子邮件</el-checkbox>
                <el-checkbox v-model="riskSettings.notifyMethods.sms">短信</el-checkbox>
                <el-checkbox v-model="riskSettings.notifyMethods.mobile">移动应用</el-checkbox>
                <el-checkbox v-model="riskSettings.notifyMethods.webhook">Webhook</el-checkbox>
              </div>
            </el-form-item>
            <el-form-item label="自动风险缓解措施">
              <div class="risk-measures">
                <el-checkbox v-model="riskSettings.measures.stopStrategy">停止策略</el-checkbox>
                <el-checkbox v-model="riskSettings.measures.reducePosition">降低仓位</el-checkbox>
                <el-checkbox v-model="riskSettings.measures.autoHedge">自动对冲</el-checkbox>
              </div>
            </el-form-item>
          </el-form>
        </div>
        <div class="settings-section">
          <div class="section-title">通知接收人</div>
          <el-table :data="notifyUsers" style="width: 100%">
            <el-table-column prop="user" label="用户" />
            <el-table-column prop="role" label="角色" />
            <el-table-column prop="riskLevel" label="风险级别" />
            <el-table-column prop="notifyMethod" label="通知方式" />
            <el-table-column label="操作" width="100" fixed="right">
              <template slot-scope="scope">
                <el-button type="text" size="small">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="table-footer">
            <el-button type="primary" plain size="small" @click="handleAddUser">添加接收人</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'RiskManagement',
  data() {
    return {
      // 风险预警记录
      riskRecords: [
        {
          status: 'active',
          name: '市场风险预警',
          threshold: '±2.5%',
          createTime: '2025-04-15',
          statusText: '运行中'
        },
        {
          status: 'paused',
          name: '交易对预警',
          threshold: '±5%',
          createTime: '2025-05-02',
          statusText: '已暂停'
        },
        {
          status: 'active',
          name: '系统性预警',
          threshold: '±3%',
          createTime: '2025-05-10',
          statusText: '运行中'
        }
      ],

      // 风险分析数据
      riskAnalysis: [
        {
          type: 'API调用',
          count: 25,
          trend: 1.2,
          level: '高风险',
          suggestion: '建议优化API调用，避免频繁请求'
        },
        {
          type: '合约风险',
          count: 15,
          trend: 1.5,
          level: '高风险',
          suggestion: '多币种分散，避免单一资产'
        },
        {
          type: '价格波动监控',
          count: 42,
          trend: -2.8,
          level: '中风险',
          suggestion: '调整止损设置，优化风控参数'
        },
        {
          type: '流动性监控',
          count: 16,
          trend: -1.5,
          level: '中风险',
          suggestion: '优化交易时间，避开低流动性'
        },
        {
          type: 'API错误',
          count: 23,
          trend: -1.2,
          level: '低风险',
          suggestion: '多个API备用，分散访问'
        }
      ],

      // 风险设置
      riskSettings: {
        checkFrequency: '5min',
        handleMode: 'auto',
        notifyMethods: {
          email: true,
          sms: true,
          mobile: false,
          webhook: false
        },
        measures: {
          stopStrategy: true,
          reducePosition: true,
          autoHedge: false
        }
      },

      // 通知接收人
      notifyUsers: [
        {
          user: '管理员',
          role: '系统管理员',
          riskLevel: '所有',
          notifyMethod: '邮件, 短信'
        },
        {
          user: '交易主管',
          role: '风控负责人',
          riskLevel: '中危及以上',
          notifyMethod: '邮件, 短信, 应用'
        },
        {
          user: '策略开发者',
          role: '开发',
          riskLevel: '高危及以上',
          notifyMethod: '邮件, 应用'
        }
      ],

      // 图表实例
      charts: {
        distribution: null,
        trend: null
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts()
    })
  },
  beforeDestroy() {
    this.disposeCharts()
  },
  methods: {
    getStatusType(status) {
      const typeMap = {
        active: 'success',
        paused: 'warning',
        stopped: 'danger'
      }
      return typeMap[status] || 'info'
    },
    getRiskLevelType(level) {
      const typeMap = {
        '高风险': 'danger',
        '中风险': 'warning',
        '低风险': 'info'
      }
      return typeMap[level] || 'info'
    },
    handleRecord(record) {
      console.log('编辑记录:', record)
    },
    initCharts() {
      // 初始化风险分布图表
      this.charts.distribution = echarts.init(this.$refs.riskDistribution)
      this.charts.distribution.setOption({
        title: {
          text: '风险来源分析',
          left: 'center',
          top: 20
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          top: 'middle'
        },
        series: [
          {
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '20',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              { value: 40, name: 'API风险' },
              { value: 28, name: '合约风险' },
              { value: 32, name: '波动风险' }
            ]
          }
        ]
      })

      // 初始化风险趋势图表
      this.charts.trend = echarts.init(this.$refs.riskTrend)
      this.charts.trend.setOption({
        title: {
          text: '风险趋势分析',
          left: 'center',
          top: 20
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: [
          {
            name: '风险指数',
            type: 'line',
            smooth: true,
            data: [60, 55, 65, 70, 65, 75, 85],
            markLine: {
              data: [
                {
                  name: '警戒线',
                  yAxis: 80,
                  lineStyle: { color: '#F56C6C' }
                }
              ]
            }
          }
        ]
      })
    },
    disposeCharts() {
      Object.values(this.charts).forEach(chart => {
        if (chart) {
          chart.dispose()
        }
      })
    },
    handleAddUser() {
      // 处理添加用户逻辑
      console.log('添加接收人')
    }
  }
}
</script>

<style lang="scss" scoped>
.risk-container {
  padding: 20px;
  background-color: #f5f7fa;

  .risk-overview-card,
  .risk-alerts-card,
  .risk-records-card,
  .risk-analysis-card,
  .risk-settings-card {
    background: #fff;
    border-radius: 4px;
    margin-bottom: 20px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);

    .card-header {
      padding: 15px 20px;
      border-bottom: 1px solid #ebeef5;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .title {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }

      .actions {
        display: flex;
        gap: 10px;
        align-items: center;
      }
    }
  }

  .risk-overview-card {
    background: #fff;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);

    .overview-content {
      padding: 24px;
      display: flex;
      justify-content: space-between;

      .overview-item {
        flex: 1;
        position: relative;
        padding: 0 24px;

        &:not(:last-child)::after {
          content: '';
          position: absolute;
          right: 0;
          top: 50%;
          transform: translateY(-50%);
          height: 50px;
          width: 1px;
          background-color: #ebeef5;
        }

        .item-label {
          color: #909399;
          font-size: 14px;
          margin-bottom: 12px;
        }

        .score-box {
          .score-value {
            display: flex;
            align-items: baseline;
            margin-bottom: 8px;

            .main-score {
              font-size: 32px;
              font-weight: 500;
              color: #ff6b00;
              line-height: 1;
            }

            .divider {
              font-size: 24px;
              color: #909399;
              margin: 0 2px;
            }

            .total-score {
              font-size: 24px;
              color: #909399;
            }
          }

          .score-bar {
            height: 4px;
            position: relative;
            margin-bottom: 8px;

            .progress-bg {
              position: absolute;
              width: 100%;
              height: 100%;
              background-color: #f5f7fa;
              border-radius: 2px;
            }

            .progress {
              position: absolute;
              height: 100%;
              background-color: #ff6b00;
              border-radius: 2px;
              transition: width 0.3s ease;
            }
          }
        }

        .score-desc {
          color: #606266;
          font-size: 13px;
        }

        .alert-count {
          font-size: 32px;
          font-weight: 500;
          color: #303133;
          margin-bottom: 8px;
          line-height: 1;
        }

        .alert-details {
          display: flex;
          gap: 12px;
          flex-wrap: wrap;

          .alert-type {
            font-size: 13px;
            color: #606266;

            .count {
              font-weight: 500;

              &.severe { color: #F56C6C; }
              &.high { color: #E6A23C; }
              &.medium { color: #409EFF; }
              &.low { color: #67C23A; }
            }
          }
        }

        .protection-box {
          .protection-value {
            font-size: 32px;
            font-weight: 500;
            color: #67C23A;
            margin-bottom: 8px;
            line-height: 1;
          }

          .protection-bar {
            height: 4px;
            position: relative;
            margin-bottom: 8px;

            .progress-bg {
              position: absolute;
              width: 100%;
              height: 100%;
              background-color: #f5f7fa;
              border-radius: 2px;
            }

            .progress {
              position: absolute;
              height: 100%;
              background-color: #67C23A;
              border-radius: 2px;
              transition: width 0.3s ease;
            }
          }
        }

        .protection-desc {
          color: #606266;
          font-size: 13px;
        }

        .warning-count {
          font-size: 32px;
          font-weight: 500;
          color: #303133;
          margin-bottom: 8px;
          line-height: 1;
        }

        .warning-trend {
          font-size: 13px;
          color: #606266;

          .trend-value {
            font-weight: 500;

            &.up {
              color: #F56C6C;
            }

            &.down {
              color: #67C23A;
            }
          }
        }
      }
    }
  }

  .risk-alerts-card {
    .alerts-list {
      padding: 10px 20px;

      .alert-item {
        display: flex;
        align-items: center;
        padding: 15px 0;
        border-bottom: 1px solid #ebeef5;

        &:last-child {
          border-bottom: none;
        }

        i {
          font-size: 20px;
          margin-right: 15px;
        }

        &.danger i {
          color: #F56C6C;
        }

        &.warning i {
          color: #E6A23C;
        }

        &.info i {
          color: #909399;
        }

        .alert-content {
          flex: 1;
          margin-right: 15px;

          .alert-title {
            font-size: 14px;
            color: #303133;
            margin-bottom: 5px;
          }

          .alert-time {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
  }

  .risk-records-card {
    .records-content {
      padding: 20px;

      .status-dot {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        margin: 0 auto;

        &.active {
          background-color: #67C23A;
        }

        &.paused {
          background-color: #E6A23C;
        }

        &.stopped {
          background-color: #F56C6C;
        }
      }
    }
  }

  .risk-analysis-card {
    .analysis-content {
      padding: 20px;

      .chart-container {
        display: flex;
        margin-bottom: 20px;

        .pie-chart,
        .line-chart {
          flex: 1;
          height: 300px;
        }
      }

      .up {
        color: #67C23A;
      }

      .down {
        color: #F56C6C;
      }
    }
  }

  .risk-settings-card {
    .settings-content {
      padding: 20px;

      .settings-section {
        margin-bottom: 30px;

        .section-title {
          font-size: 14px;
          font-weight: 500;
          color: #303133;
          margin-bottom: 20px;
        }

        .notify-options,
        .risk-measures {
          display: flex;
          gap: 20px;
        }

        .table-footer {
          margin-top: 15px;
          display: flex;
          justify-content: flex-start;
        }
      }

      .el-form {
        max-width: 600px;
      }

      .el-table {
        margin-top: 10px;
      }
    }
  }
}
</style>